package com.ezerg.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import com.ezerg.util.ConfigUtil;

public class RedisPool {
	private static RedisPool redisPool = new RedisPool();
	
	private JedisPool pool;

	private RedisPool() {
		// 加载redis配置文件
		ConfigUtil cu = new ConfigUtil("redis");
		// 创建jedis池配置实例
		JedisPoolConfig config = new JedisPoolConfig();
		// 设置池配置项值
		config.setMaxTotal(cu.getInt("jedis.pool.maxActive", 250));
		config.setMaxIdle(cu.getInt("jedis.pool.maxIdle", 25));
		config.setMaxIdle(cu.getInt("jedis.pool.maxWait", 1000));
		config.setTestOnBorrow(cu.getBoolean("jedis.pool.testOnBorrow", false));
		config.setTestOnReturn(cu.getBoolean("jedis.pool.testOnReturn", false));
		// 根据配置实例化jedis池
		String ip = cu.getString("redis.ip", "localhost");
		int port = cu.getInt("redis.port", 6379);
		int timeout = cu.getInt("redis.timeout", 2000);
		String password = cu.getString("redis.password", null);;
		int database = cu.getInt("redis.database", 0);;
		//
		pool = new JedisPool(config, ip, port, timeout, password, database);
	}
	
	public static RedisPool get() {
		return redisPool;
	}
	
	public JedisPool getPool() {
		return pool;
	}
	
    public Jedis getResource() {
        return pool.getResource();
    }
    
    public Jedis getResource(int index) {
    	Jedis jedis = pool.getResource();
    	jedis.select(index);
        return jedis;
    }
    
    public void returnResource(Jedis jedis, boolean error) {
        if (error) {
        	pool.returnBrokenResource(jedis);
        } else {
        	pool.returnResource(jedis);
        }
      }

    public void returnResource(Jedis jedis) {
    	returnResource(jedis, false);
    }

    public void destroy() {
    	pool.destroy();
    }
}
